package com.lzy.blog.controller;

import com.lzy.blog.enums.ResultEnum;
import com.lzy.blog.pojo.Blog;
import com.lzy.blog.service.BlogService;
import com.lzy.blog.utils.PageUtils;
import com.lzy.blog.utils.Result;
import com.lzy.blog.utils.StringUtils;
import com.lzy.blog.vo.BlogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: lzy_blog
 * @description: 博客的相关功能
 * @author: lzy
 * @create: 2020-07-05 22:34
 **/
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    /**
     * 添加
     * @param blog
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Result<Object> save(@RequestBody Blog blog){
        blogService.save(blog);
        return new Result<>("添加成功！");
    }

    /**
     * 根据id查询  后台用户
     * @return
     */
    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    public Result<Blog> get(@PathVariable String id){
        Blog blog = blogService.getById(id);
        return new Result<>(blog);
    }

    /**
     * 更新
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    public Result<Object> update(@RequestBody Blog blog){
        blogService.update(blog);
        return new Result<>("更新成功！");
    }

    /**
     * 根据id查询，阅读
     * @param id
     * @return
     */
    @RequestMapping(value = "/read/{id}",method = RequestMethod.GET)
    public Result<BlogVo> read(@PathVariable String id){
        BlogVo blog = blogService.readById(id);
        return new Result<>(blog);
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
    public Result<Object> delete(@PathVariable String id){
        blogService.deleteById(id);
        return new Result<>("删除成功");
    }

    /**
     * 分页查询
     * @param page
     * @return
     */
    @RequestMapping(value = "/getByPage",method = RequestMethod.POST)
    public Result<PageUtils<BlogVo>> getByPage(@RequestBody PageUtils<BlogVo> page){
        String sortColumn = page.getSortColumn();
        //判断排序列是否为空
        if(StringUtils.isNotBlank(sortColumn)){
            //不为空，用数组存储可以用来排序的字段
            String[] columns = {"blog_goods","blog_read","blog_collection",
                    "type_name","blog_comment","created_time","update_time"};
            List<String> sortList = Arrays.asList(columns);
            //如果集合中不包含排序的字段
            if(!sortList.contains(sortColumn.toLowerCase())){
                return new Result<>(ResultEnum.PARAMS_ERROR.getCode(),"排序的参数不合法！");
            }
        }
        page = blogService.getByPage(page);
        return new Result<>(page);
    }
}
